//
//  PrefsV2UnitsViewController.m
//  Fuel Log 4
//
//  Created by Olaf on 22.05.10.
//  Copyright 2010 olafgreck. All rights reserved.
//

#import "PrefsTextSubViewController.h"
#import "PrefsV2ViewController.h" 
#import "FuelLogAppDelegate.h"
#import "Pref.h"

#import "DebugOutput.h"
 
#warning verify passwordString and sernameString are correctly populated and retained


@class SFHFKeychainUtils;

@implementation PrefsTextSubViewController

@synthesize accountToWorkOn;
@synthesize doneButton;
@synthesize userNameString, passWordString; 
@synthesize textFieldBeingEdited;

#pragma mark -
#pragma mark TextFields

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"inside textFieldDidBeginEditing");
    self.textFieldBeingEdited = textField;
}	
 
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
	debug(@"in textFieldShouldEndEditing ");
	return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
	debug(@"in textFieldDidEndEditing , textField.tag: %d", textField.tag);
	if (textField.tag == prefRow_Username) 
	{
		[self setUserNameString:[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
		if (([userNameString rangeOfString:@"@"].location == NSNotFound) && 
			[accountToWorkOn isEqualToString:_onlineServiceNameGoogleDocs] &&
			[userNameString length] > 0) 
		{
			[self setUserNameString:[userNameString stringByAppendingString:@"@gmail.com"]];
		}
		[textField setText:userNameString];
		debug(@"userNameString: %@", userNameString);
	}
	if (textField.tag == prefRow_Password) [self setPassWordString:textField.text];
}


-(BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered {
//	debug(@"in shouldChangeCharactersInRange");
	NSCharacterSet * myCharSet = [NSCharacterSet characterSetWithCharactersInString:@" "];
	if (textField.tag == prefRow_Username)
	{
		for (int i = 0; i < [textEntered length]; i++) {
			unichar c = [textEntered characterAtIndex:i];
			if ([myCharSet characterIsMember:c]) {
				return NO;
			}
		}
	}
/*		self.userNameString = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	}
	if (textField.tag == prefRow_Password) 
	{
		self.passWordString = textField.text;
	}*/
	return YES;
}	
	

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	debug(@"in textFieldShouldReturn, %d",  textField.tag);
	if (textField.tag == prefRow_Username ) [self setUserNameString:textField.text];
	if (textField.tag == prefRow_Password ) [self setPassWordString:textField.text];
	[textField resignFirstResponder];
	return YES;
}

#pragma mark -
- (IBAction)done:(id)sender {  
	debug(@"in done");
	if (self.textFieldBeingEdited != nil) {
        [self textFieldDidEndEditing:textFieldBeingEdited];
        self.textFieldBeingEdited = nil;
    }
	NSError *error = nil;
	[SFHFKeychainUtils storeUsername:_username andPassword:userNameString
					  forServiceName:accountToWorkOn
					  updateExisting:YES error:&error];
	[SFHFKeychainUtils storeUsername:_password andPassword:passWordString
					  forServiceName:accountToWorkOn
					  updateExisting:YES error:&error];
	if (error != nil) debug(@"Error saving credentails %@",error);
  
	debug(@"userNameString: %@",  userNameString);
	debug(@"passWordString: %@",  passWordString);
/*	[GDataHTTPFetcher setIsLoggingEnabled:YES]; 
	GoogleDataWrapper * googleDataWrapper = [GoogleDataWrapper alloc];
	[googleDataWrapper uploadBlankSpreadsheetToDocListFeed:(GDataFeedDocList *)docListFeed];
	*/
	[self.navigationController popViewControllerAnimated:YES];
}
// */

- (id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
		doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
																   target:self
																   action:@selector(done:)];
		self.navigationItem.rightBarButtonItem = doneButton;
		self.navigationItem.title = (NSLocalizedString(@"Preferences", @"Preferences"));
    }
  	return self;
}

 

/*
 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to preserve selection between presentations.
 self.clearsSelectionOnViewWillAppear = NO;
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 */


- (void)viewWillAppear:(BOOL)animated {
	debug(@"in viewWillAppear");
	[(UIScrollView*)[self view] setScrollEnabled:NO];
	
	NSError *error = nil;
	/*   [SFHFKeychainUtils storeUsername:@"username" andPassword:@"userIsOlaf" 
	 forServiceName:@"GoogleDocs" 
	 updateExisting:YES error:&error];
	 [SFHFKeychainUtils storeUsername:@"password" andPassword:@"passIsWord" 
	 forServiceName:@"GoogleDocs" 
	 updateExisting:YES error:&error];
	 */	
	self.userNameString = @"";
	self.passWordString = @"";
	self.userNameString = [[SFHFKeychainUtils  getPasswordForUsername:_username 
												  andServiceName:accountToWorkOn 
														   error:&error] retain];
	if ([userNameString length] > 0 && error == 0) {
		self.passWordString =[[SFHFKeychainUtils  getPasswordForUsername:_password 
													 andServiceName:accountToWorkOn 
															  error:&error] retain];
	}
	else debug(@"Error: &@", &error);
/*	if ([userNameString length] > 0 && [passWordString length] > 0 && error == 0)
		self.navigationItem.rightBarButtonItem.enabled = YES;
	else 
		self.navigationItem.rightBarButtonItem.enabled = NO;
	*/
	debug(@"username: %@",userNameString);
	debug(@"password: %@",passWordString);
	
	//	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	//		[appDelegate setUsername:uname];
	//		[appDelegate setPassword:pw];
	//	}
	//	if ([[appDelegate username] length] == 0) userNameString = @"<not assigned>";
	//	else userNameString = [appDelegate username];
	
    [super viewWillAppear:animated];
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
	
	return  accountToWorkOn; 
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 2;
}


// Customize the appearance of table view cells.
/* // obsoleted
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	// debug(@"in cellForRowAtIndexPath");
	NSInteger row = indexPath.row;
	static NSString *CellIdentifier = @"CellType3";
	PrefsCustomCellType3 *cell = (PrefsCustomCellType3 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[PrefsCustomCellType3 alloc] initWithFrame:CGRectZero ]  autorelease];
		cell.accessoryType=UITableViewCellAccessoryNone;
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	cell.primaryLabel.text =  (NSString *)[primaryLabelStringArray objectAtIndex:row] ;
	cell.textBox.delegate = self;
	cell.textBox.tag = row;
	if (row == 0) {
		if ([userNameString length] >0) 	cell.textBox.text = userNameString;
		else	cell.textBox.placeholder =	@"example@gmail.com";
		cell.textBox.keyboardType = UIKeyboardTypeEmailAddress;
		cell.textBox.returnKeyType = UIReturnKeyNext;
	}
	if (row == 1) {
		if ([passWordString length] >0) 	cell.textBox.text =passWordString;
		else 	cell.textBox.placeholder = @"Required";
		cell.textBox.keyboardType = UIKeyboardTypeDefault;
		cell.textBox.returnKeyType = UIReturnKeyDone;
		cell.textBox.secureTextEntry = YES;
	}
	return cell;
}
*/

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"CellIdentifier";
	//debug(@"section %d, row %d", indexPath.section, indexPath.row);
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
	cell.accessoryType=UITableViewCellAccessoryNone;
	if (indexPath.section == 0) {
		CGRect frame = CGRectMake(0 ,5, 190, 30);
		
		UITextField *textField = [[[UITextField alloc] initWithFrame:frame] autorelease];
		textField.clearsOnBeginEditing = NO;
		textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
		textField.textAlignment = UITextAlignmentRight;
		textField.textColor = [UIColor colorWithRed:0.22 green:0.329 blue:0.529 alpha:1];
		textField.clearButtonMode =	UITextFieldViewModeWhileEditing;
		textField.borderStyle =UITextBorderStyleRoundedRect;
		textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;  
		textField.returnKeyType = UIReturnKeyDone; //   cannot reach next field
		textField.delegate = self;
		textField.tag = indexPath.row; 
		
		switch (indexPath.row) {
			case 0: // username will have UITextField
				cell.textLabel.text = (NSLocalizedString(@"Username", @"Username"));
				if ([userNameString length] >0) 	textField.text = userNameString;
				else	textField.placeholder =	@"example@gmail.com";
				textField.keyboardType = UIKeyboardTypeEmailAddress;
				textField.returnKeyType = UIReturnKeyNext;
				
				[cell setAccessoryView:textField];
				break;
			case 1:		// Password, will have UITextField
				cell.textLabel.text = (NSLocalizedString(@"Password", @"Password"));
				if ([passWordString length] >0) 	textField.text =passWordString;
				else 	textField.placeholder = @"Required";
				textField.keyboardType = UIKeyboardTypeDefault;
				textField.returnKeyType = UIReturnKeyDone;
				textField.secureTextEntry = YES;
				[cell setAccessoryView:textField];
				break;
 
			default:
				break;
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
	}
	 	return cell;
}



/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	[tableView reloadData];
	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[accountToWorkOn release];
	[doneButton release]; 
	[userNameString release];
	[passWordString release];
    [super dealloc];
}


@end

